<template>
  <div class="searchBanner">
    <div class="searchInput">
      <el-autocomplete class="search-input" v-model="input" :fetch-suggestions="querySearch" placeholder="搜索音乐、歌手、歌单、MV" prefix-icon="el-icon-search" clearable @focus="hotList" @keydown.enter.native="searchMsg()" @select="handleSelect"></el-autocomplete>
      <ul>
        <li>热门搜索：</li>
        <li v-for="(item,i) in hotSearchList" :key="i" @click="searchBriefMsg(item.first)">
          {{item.first}}
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { getHotSearchBrief } from "../../network/search"
import { getHotList } from "../../network/home"

export default {
  name: "SearchBanner",
  data() {
    return {
      input: "",
      hotSearchList: "",
      hots: []
    }
  },
  created() {
    this.getHotSearchBrief();
  },
  mounted() {
    //获取navbar搜索框内容 填入当前搜索框 
    this.input = sessionStorage.getItem("songTitle");
    this.restaurants = this.hots;
  },
  methods: {
    searchMsg() {
      //将搜索框内容放入sessionStorage
      sessionStorage.setItem("songTitle", this.input);
      //刷新页面 input传入过去 其中内容改了 但是页面还是原来的 需要刷新显示
      location.reload()
    },
    searchBriefMsg(songTitle) {
      //将搜索内容内容放入sessionStorage
      sessionStorage.setItem("songTitle", songTitle);
      //刷新页面 input传入过去 其中内容改了 但是页面还是原来的 需要刷新显示
      location.reload()
    },
    getHotSearchBrief() {
      getHotSearchBrief().then(res => {
        this.hotSearchList = res.data.result.hots.slice(0, 5);
      })
    },
    hotList() {
      getHotList().then(res => {
        //将返回结果作为对象循环遍历到hots数组中，为querySearch使用
        //console.log(res.data);
        for (var i = 0; i < res.data.result.hots.length; i++) {
          this.hots.push({ value: res.data.result.hots[i].first });
        }
      })
    },
    // fetch-suggestions	 返回输入建议的方法，仅当你的输入建议数据 resolve 时，通过调用 cb(data:[]) 来返回它
    querySearch(queryString, cb) {
      //queryString 为选中的建议项
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    // 点击选中建议项时触发handleSelect
    handleSelect() {
      //搜索该项，并跳转到search
      this.searchMsg();
    }
  },
}
</script>

<style scoped>
.searchBanner {
  width: 100%;
  height: 200px;
  background-image: url("../../assets/img/searchBanner.jpg");
  background-size: 100% 100%;
}
.searchInput {
  width: 40%;
  padding: 80px 0 0 31%;
}
.search-input {
  width: 100%;
}
.searchInput ul {
  list-style-type: none;
}
.searchInput ul li {
  float: left;
  color: RGB(255, 255, 255);
  margin-left: 10px;
}
.searchInput ul li:hover {
  color: RGB(64, 158, 255);
}
</style>